package no.sogl.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class PersonTag {
	@NotNull
    @ManyToOne
    private Person person;

    @NotNull
    @ManyToOne
    private Tag tag;
        
	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	@Column(updatable = false, insertable = true)
	private Date createdAt = new Date();

	public PersonTag() {
		super();
	}

	public PersonTag(Person person, Tag tag) {
		super();
		this.person = person;
		this.tag = tag;
	}

	public static PersonTag findPersonTagByTag(Tag tag) {
		if (tag == null)
			throw new IllegalArgumentException("The tag argument is required");
		EntityManager em = PersonTag.entityManager();
		TypedQuery<PersonTag> q = em.createQuery(
				"SELECT o FROM PersonTag AS o WHERE o.tag = :tag", PersonTag.class)
				.setMaxResults(1);
		q.setParameter("tag", tag);
		try {
			return q.getSingleResult();
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	
	public String toString(){
	    return getTag().getName();
	}
}
